<template>
    <div>
        <form class="form-signin" @submit.prevent="login">
            <h1 class="h3 mb-3 text-center font-weight-normal">后台管理</h1>
            <label for="inputEmail" class="sr-only">账号...</label>
            <input type="text" id="inputEmail" v-model="account" class="mb-1 form-control" placeholder="账号" required autofocus>
            <label for="inputPassword" class="sr-only">密码...</label>
            <input type="password" id="inputPassword" v-model="password" class="form-control" placeholder="密码" required>
            <div v-show="error" class="alert alert-danger" role="alert">
                {{error}}
            </div>
            <button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
            <p class="mt-5 mb-3 text-muted text-center">&copy; 2017-2018</p>
        </form>
    </div>
</template>

<script>
import AuthenticationService from '../../services/AuthenticationService'

export default {
  name: 'Login',
  data () {
    return {
      account: '',
      password: '',
      error: null
    }
  },
  created: function () {
    this.$emit('switchAdmin', true)
    if (this.$root.$store.state.isAdminLoggedIn) {
      this.$router.push('/Admin')
    }
  },
  methods: {
    async login () {
      try {
        const response = await AuthenticationService.AdminLogin({
          account: this.account,
          password: this.password
        })

        this.error = null
        this.$store.dispatch('setToken', response.data.token)
        sessionStorage.setItem('token', response.data.token)
        this.$router.push('/Admin')
        // this.$store.dispatch('setAdmin', response.data.admin)
      } catch (e) {
        this.error = e.response.data.error
      }
    }
  }
}
</script>

<style scoped>
    html,
    body {
        height: 100%;
    }

    body {
        display: -ms-flexbox;
        display: flex;
        -ms-flex-align: center;
        align-items: center;
        padding-top: 40px;
        padding-bottom: 40px;
        background-color: #f5f5f5;
    }

    .form-signin {
        width: 100%;
        max-width: 330px;
        padding: 15px;
        margin: auto;
    }
    .form-signin .checkbox {
        font-weight: 400;
    }
    .form-signin .form-control {
        position: relative;
        box-sizing: border-box;
        height: auto;
        padding: 10px;
        font-size: 16px;
    }
    .form-signin .form-control:focus {
        z-index: 2;
    }
    .form-signin input[type="email"] {
        margin-bottom: -1px;
        border-bottom-right-radius: 0;
        border-bottom-left-radius: 0;
    }
    .form-signin input[type="password"] {
        margin-bottom: 10px;
        border-top-left-radius: 0;
        border-top-right-radius: 0;
    }
</style>
